<template>
    <BasePage>
        <el-form slot="form" :inline="true" size="medium" @submit.native.prevent>
            <el-form-item label="公路名称">
                <RoadSelect :value.sync="form.highwayName" :is-label="true" placeholder="请选择" clearable />
            </el-form-item>
            <el-form-item label="年度">
                <el-date-picker v-model="form.year" type="year" value-format="yyyy" :editable="false" placeholder="请选择" />
            </el-form-item>
            <el-form-item label="管理机构">
                <el-cascader
                    v-model="form.orgs"
                    :props="props"
                    :options="orgOptions"
                    clearable
                    :show-all-levels="false"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="setOrgId"
                />
            </el-form-item>
            <el-form-item>
                <BaseButton v-permission="{ btnCode: 'dlyh_c13_d45_2' }" @click="handleFilter">查询</BaseButton>
                <BaseButton type="second" @click="resetConditions">重置</BaseButton>
            </el-form-item>
        </el-form>

        <div slot="button">
            <BaseButton v-permission="{ btnCode: 'dlyh_c13_d47_2' }" @click="showDialog()">新建年度预算</BaseButton>
            <FormDialog
                ref="dateDialog"
                title="请选择公路"
                :items="formItems"
                :rules="dialogRules"
                :form.sync="dialogForm"
                :visible.sync="dialogVisible"
                @submit="handleAdd"
            />
        </div>

        <!--数据列表区-->
        <BaseTable slot="table" v-loading="listLoading" :columns="columns" :data="list" row-key="id" height="calc(100% - 73px)" highlight-current-row>
            <template #number="{ scope: { row } }">
                <BaseButton type="text" @click="handleDetail(row)">{{ row.number }}</BaseButton>
            </template>
            <template #type="{ scope: { row } }">
                <span :style="`color:${changeTypesColor[row.changeType]};`">{{ changeTypes[row.changeType] }}</span>
            </template>
            <template #status="{ scope: { row } }">
                <span :style="`color:${statusColor[row.status]};`">{{ row.status | value2Name(checkTypes) }}</span>
            </template>
            <template #orgDept="{ scope: { row } }">
                <span>{{ row.orgDept || '-' }}</span>
            </template>
            <template #handle="{ scope: { row } }">
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c13_d49_2' }" type="text" @click="handleSubmit(row.number)">
                    提交
                </BaseButton>
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c13_d50_2' }" type="text" @click="handleEdit(row)">编辑</BaseButton>
                <BaseButton v-show="row.status === 0" v-permission="{ btnCode: 'dlyh_c13_d51_2' }" type="text" color="danger" @click="handleDelete(row.id)">
                    删除
                </BaseButton>

                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c13_d49_2' }" type="text" @click="handlerecall(row.number)">
                    撤回
                </BaseButton>

                <BaseButton v-show="row.status === 1" v-permission="{ btnCode: 'dlyh_c13_d118_2' }" type="text" @click="handleCheck(row)">审核</BaseButton>
                <BaseButton v-show="row.status === 2" v-permission="{ btnCode: 'dlyh_c13_d119_2' }" type="text" @click="handleApproval(row)">批复</BaseButton>
                <BaseButton v-show="row.status === 3 && !row.month" v-permission="{ btnCode: 'dlyh_c13_d48_2' }" type="text" @click="handleAdd(row)">
                    新建下级
                </BaseButton>
                <!-- 变更功能下期迭代开发 -->
                <!-- <BaseButton v-if="row.status === 3 && row.recordType !==2" type="text" @click="submitChange(row)">提交变更</BaseButton>
                <BaseButton v-if="row.status === 3 && row.recordType === 2" type="text" @click="checkChange(row)">查看变更</BaseButton> -->
            </template>
        </BaseTable>
        <!--分页组件-->
        <Pagination
            slot="pagination"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @current-change="getList"
            @size-change="getList"
        />
    </BasePage>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { BudgetingOldModel, OrgModel, RoadModel } from '@/models'
import reconfirm from '@/utils/reconfirm'
import { CheckTypes, StatusColor, ChangeTypes, ChangeTypesColor } from '@/config/constants'
import { value2Name } from '@/filters'
import KeepAliveHandler from '@/mixins/keepAliveHandler'

export default {
    name: 'BudgetingIndex',
    components: {
        BasePage
    },
    filters: {
        value2Name
    },
    mixins: [
        KeepAliveHandler({
            defaultCondition: {
                highwayName: null,
                year: null,
                orgs: [],
                orgId: null
            },
            conditionObjKey: 'form'
        })
    ],
    data() {
        return {
            checkTypes: CheckTypes,
            statusColor: StatusColor,
            changeTypes: ChangeTypes,
            changeTypesColor: ChangeTypesColor,
            model: new BudgetingOldModel(),
            orgModel: new OrgModel(),
            roadModel: new RoadModel(),
            form: {
                highwayName: null,
                year: null,
                orgs: []
            },
            orgOptions: [],
            props: {
                value: 'id',
                label: 'name',
                checkStrictly: true
            },
            dialogVisible: false,
            dialogForm: {},
            formItems: [],
            dialogRules: {
                roadCode: [{ required: true, message: '请选择公路', trigger: ['blur', 'change'] }]
            },
            listLoading: true,
            list: [],
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: Object.freeze([
                {
                    slot: 'number',
                    attrs: {
                        prop: 'number',
                        label: '编号',
                        width: '220',
                        'show-overflow-tooltip': true,
                        fixed: 'left'
                    }
                },
                {
                    attrs: {
                        prop: 'highwayName',
                        label: '公路名称',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'cycle',
                        label: '周期',
                        'show-overflow-tooltip': true,
                        width: '140'
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        prop: 'recordType',
                        label: '类型',
                        width: '100',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'orgDept',
                    attrs: {
                        prop: 'orgDept',
                        label: '管理机构',
                        'show-overflow-tooltip': true,
                        'min-width': '180'
                    }
                },
                {
                    attrs: {
                        prop: 'routeLength',
                        label: '路线长度（km）',
                        'show-overflow-tooltip': true,
                        width: '180'
                    }
                },
                {
                    attrs: {
                        prop: 'total',
                        label: '合计（元）',
                        'show-overflow-tooltip': true,
                        width: '160'
                    }
                },
                {
                    slot: 'status',
                    attrs: {
                        prop: 'status',
                        label: '状态',
                        width: '120',
                        'show-overflow-tooltip': true,
                        fixed: 'right'
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        'min-width': '250',
                        fixed: 'right'
                    }
                }
            ]),
            userId: null,
            year: null,
            budgetType: 1, // 预算类型 1-年度预算，2-季度预算，3-月度预算
            roadCode: null,
            number: null,
            roadOptions: []
        }
    },
    created() {
        this.userId = this.$store.getters.avatar.id
        this.getOrgAll()
        this.getList()
        this.getRoadList()
    },
    methods: {
        getRoadName(val) {
            let road = {}
            this.roadOptions.some((item) => {
                if (val === item.value) {
                    // 后端需要添加路段长度、管养机构orgId和orgDept参数
                    road = {
                        roadCode: item.value,
                        highwayName: item.label,
                        routeLength: item.totalLength,
                        orgId: item.orgId,
                        orgDept: item.orgDept
                    }
                    return true
                }
            })
            return road
        },
        getRoadList() {
            this.roadModel.getList({}, { pageSize: 1000 }).then((res) => {
                this.roadOptions = res.list.map((item) => {
                    return {
                        value: item.highwayCode,
                        label: item.highwayName,
                        totalLength: item.totalLength,
                        orgId: item.sysManagementOrgId,
                        orgDept: item.sysManagementOrgName
                    }
                })
            })
        },
        handleCheck(row) {
            this.$router.push({
                name: 'BudgetingAudit',
                query: {
                    number: row.number,
                    belongItem: 1,
                    type: row.recordType,
                    budgetType: row.budgetType,
                    audit: true
                }
            })
        },
        handleApproval(row) {
            // belongItem所属项(1-养护预算、2-养护计划、3-计划实施、4-路产赔付、5-巡查计划)
            this.$router.push({
                name: 'BudgetingApproval',
                query: {
                    number: row.number,
                    belongItem: 1,
                    type: row.recordType,
                    budgetType: row.budgetType,
                    audit: true,
                    approval: true
                }
            })
        },
        handlerecall(number) {
            reconfirm({
                text: '是否确定撤回表单',
                callback: () => this.recall(number)
            })
        },
        recall(number) {
            return this.model
                .recall(number)
                .then(() => {
                    this.getList()
                    this.$message.success('撤回成功！')
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        handleSubmit(number) {
            reconfirm({
                text: '是否确认提交表单',
                callback: () => this.submit(number)
            })
        },
        submit(number) {
            return this.model
                .submit(number)
                .then(() => {
                    this.getList()
                    this.$message.success('提交成功！')
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 机构筛选框变化时，把默认的orgs数组处理成origId参数
        setOrgId(val) {
            if (val.length > 0) {
                this.form.orgId = val[val.length - 1]
            } else {
                this.form.orgId = null
            }
        },
        // 获取机构下拉项
        getOrgAll() {
            this.orgModel.getListAll().then((res) => {
                this.orgOptions = res
            })
        },
        getList() {
            this.listLoading = true
            this.model
                .getList(this.form, this.page)
                .then((res) => {
                    this.list = res.list
                    this.page.total = res.totalCount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 查询
        handleFilter() {
            this.page.pageNo = 1
            this.getList()
        },
        handleDelete(id) {
            reconfirm({
                callback: () => this.delete(id)
            })
        },
        delete(id) {
            return this.model.delete({ id }).then(() => {
                this.getList()
                this.$message.success('删除成功!')
            })
        },
        handleDetail(row) {
            this.$router.push({
                path: 'detail',
                query: {
                    number: row.number,
                    budgetType: row.budgetType
                }
            })
        },
        // 提交变更
        submitChange(row = {}) {
            switch (row.budgetType) {
                case 1:
                    this.$router.push({ path: 'change', query: { type: 'change', number: row.number } })
                    break
                case 2:
                    this.$router.push({
                        path: 'quarter-change',
                        query: {
                            type: 'change',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            roadCode: row.roadCode
                        }
                    })
                    break
                case 3:
                    this.$router.push({
                        path: 'month-change',
                        query: {
                            type: 'change',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            month: row.month,
                            roadCode: row.roadCode
                        }
                    })
                    break
            }
        },
        // 查看变更
        checkChange(row) {
            this.$router.push({ path: 'detail', query: { number: row.changeNumber, budgetType: row.budgetType, recordType: row.recordType } })
        },
        showDialog() {
            this.dialogForm = {}
            this.formItems = [
                {
                    type: 'select',
                    model: 'roadCode',
                    label: '公路',
                    options: this.roadOptions
                }
            ]
            this.$refs['dateDialog'].show()
        },
        handleAdd(row) {
            this.dialogVisible = false
            // row会是新建年度的验证规则通过的结果valid，也可能是新建下级传过来的行数据
            if (row !== false) {
                this.budgetType = row.budgetType ? row.budgetType + 1 : 1

                let road = row.roadCode
                    ? {
                        roadCode: row.roadCode,
                        highwayName: row.highwayName,
                        routeLength: row.routeLength || null,
                        orgId: row.orgId || null,
                        orgDept: row.orgDept || null
                    }
                    : this.getRoadName(this.dialogForm.roadCode)
                // 对road对象做下转义
                road = encodeURIComponent(JSON.stringify(road))

                switch (this.budgetType) {
                    case 1: {
                        this.$router.push({
                            path: 'add',
                            query: {
                                type: 'add',
                                number: this.number,
                                road
                            }
                        })
                        break
                    }
                    case 2:
                        this.$router.push({
                            path: 'quarter-add',
                            query: {
                                type: 'add',
                                number: this.number,
                                year: row.year,
                                budgetType: 2,
                                road
                            }
                        })
                        break
                    case 3:
                        this.$router.push({
                            path: 'month-add',
                            query: {
                                type: 'add',
                                number: this.number,
                                year: row.year,
                                quarter: row.quarter,
                                budgetType: 3,
                                road
                            }
                        })
                        break
                }
            }
        },
        handleEdit(row) {
            switch (row.budgetType) {
                case 1:
                    console.log(!!row.changeId)
                    this.$router.push({
                        path: 'edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            change: row.changeId
                        }
                    })
                    break
                case 2:
                    this.$router.push({
                        path: 'quarter-edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            year: row.year,
                            roadCode: row.roadCode,
                            budgetType: 2,
                            change: row.changeId
                        }
                    })
                    break
                case 3:
                    this.$router.push({
                        path: 'month-edit',
                        query: {
                            type: 'edit',
                            number: row.number,
                            year: row.year,
                            quarter: row.quarter,
                            budgetType: 3,
                            roadCode: row.roadCode,
                            change: row.changeId
                        }
                    })
                    break
            }
        }
    }
}
</script>

<style lang="scss">
</style>
